<?php
/**
 * @author    Medard <pingguoli@gmail.com>
 * @date      2019/3/4 15:04
 * @copyright Copyright 2018 - 2019
 *  
 *  
 * @version   1.0
 */

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * 角色管理
 * Class Role
 * @package App\Model
 */
class Role extends Model
{
    /**
     * @var array
     */
    protected $fillable = ['name'];

    /**
     * 授权
     * @param $data
     * @return bool
     */
    public function savePermission($data)
    {
        DB::beginTransaction();
        try {
            if (!$this) {
                throw new \Exception('');
            }
            /* 删除角色所有权限 */
            $this->rolePermissions()->delete();
            $permissions = [];
            if (!empty($data['permissions']) && is_array($data['permissions'])) {
                foreach ($data['permissions'] as $permissionId) {
                    $permissions[] = [
                        'permission_id' => $permissionId
                    ];
                }
                /* 添加权限 */
                $this->rolePermissions()->createMany($permissions);
            }

            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            return false;
        }
    }

    /**
     * 获取权限
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function permissions()
    {
        return $this->belongsToMany(Permission::class, 'role_permissions');
    }

    /**
     * 获取权限关联表
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function rolePermissions()
    {
        return $this->hasMany(RolePermission::class);
    }

    /**
     * 获取权限ID
     * @return array
     */
    public function permissionIds()
    {
        $ids = [];
        $list = $this->rolePermissions()->get();
        foreach ($list as $item) {
            $ids[] = $item->permission_id;
        }

        return $ids;
    }

    public function adminRoles(){
        return $this->hasMany(AdminRole::class);
    }

}
